import { useSnapshot } from 'valtio';
import { ProCard } from 'szcd';
import { type IControlView } from '../../controls/base';
import styles from './index.module.less';
export interface ICardView {
  title: string;
  visible: boolean;
  controls: Array<
    IControlView & {
      component: React.FC<{ service: IControlView } & React.HTMLAttributes<HTMLDivElement>>;
    }
  >;
}

const Card: React.FC<{ service: ICardView } & React.HTMLAttributes<HTMLDivElement>> = ({
  service,
  ...restProps
}) => {
  const snap = useSnapshot(service);
  return (
    <ProCard className={styles.card} title={snap.title} collapsible style={{ display: snap.visible ? undefined : 'none' }} {...restProps}>
      {/* 注意需要访问snap.controls, 否则 style={{ display: control.visible ? undefined : 'none' }}  不会生效 */}
      {/* 这样的问题是，任何controls[x].x的属性变动都会导致rerender，为了更好的性能，但这是正确的做法 */}
      {/* 理论上任何访问要走snap，不应该通过错误的方法来实现性能的优化,所以不尝试下放控制做法 */}

      {snap.controls && service.controls.map((control, key) => (
        <control.component key={key} service={control} style={{ display: control.visible ? undefined : 'none' }} />
      ))}
    </ProCard>
  );
};

export default Card;
